import axios, { AxiosRequestConfig, AxiosError } from 'axios'

const request = axios.create({
	baseURL: process.env.EXPO_PUBLIC_API_URL,
	timeout: 5000,
})

console.log('请求地址', process.env.EXPO_PUBLIC_API_URL)

// 请求拦截
request.interceptors.request.use((config) => {
	// 在发送请求之前做些什么
	const token = localStorage.getItem('token')
	if (token) {
		config.headers.Authorization = token
	}

	return config
})

// 响应拦截
request.interceptors.response.use(
	(response) => {
		// 对响应数据做点什么
		const newToken = response.headers.token
		if (newToken) {
			localStorage.setItem('token', newToken)
		}

		return response.data
	},
	(error) => {
		if (error.response) {
			return Promise.reject(error)
		}
		const { data } = error.response
		if (data?.statusCode === 401) {
			console.log('登录过期，请重新登陆')
			setTimeout(() => {
				// TODO: 跳转到登录页面
			}, 1500)
		} else {
			return Promise.reject(error)
		}
	},
)

interface ErrorResponse {
	message: string
	statusCode: number
}
type CustomResponse<T> = [boolean, T]

export const customRequest = async <T>(options: AxiosRequestConfig): CustomResponse<T> => {
	try {
		const res = await request(options)
		return [true, res.data as T]
	} catch (error) {
		const axiosError = error as AxiosError<ErrorResponse>
		const errorData = axiosError.response?.data || null
		const errorMessage = errorData?.message || axiosError.message
		console.log(errorMessage)
		return [false, errorData as T]
	}
}

export default request
